package com.erp.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.shop.domain.ErpSellerStoreRecord;
import com.erp.shop.domain.bo.ErpSellerStoreEmpowerBo;
import com.erp.shop.domain.bo.ErpSellerStoreRecordBo;
import com.erp.shop.domain.dto.ErpSellerStoreRecordDto;
import com.erp.shop.domain.vo.ErpSellerStoreRecordVo;
import com.erp.shop.mapper.ErpSellerStoreEmpowerMapper;
import com.erp.shop.mapper.ErpSellerStoreRecordMapper;
import com.erp.shop.service.IErpSellerStoreEmpowerService;
import com.erp.shop.service.IErpSellerStoreRecordService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @Description: 经公司开通或添加的所有店铺信息列表Service业务层处理
 * @Author: j.zh
 * @Date: 2024/7/6
 * @Version: 4.2.0
**/
@RequiredArgsConstructor
@Service
public class ErpSellerStoreRecordServiceImpl implements IErpSellerStoreRecordService {

    @Resource
    ErpSellerStoreRecordMapper baseMapper;
    @Resource
    IErpSellerStoreEmpowerService empowerService;

    /**
     * 查询店铺信息列表
     */
    @Override
    public TableDataInfo<ErpSellerStoreRecordDto> queryPageList(ErpSellerStoreRecordBo bo, PageQuery pageQuery) {
        ErpSellerStoreRecordDto selectDto = BeanUtil.toBean(bo, ErpSellerStoreRecordDto.class);
        Long userId = SecurityUtils.getUserId();
        if (userId != 1l){
            // 非超级管理员，按权限搜索
            selectDto.setCreateBy(userId+"");
        }
//        LambdaQueryWrapper<ErpSellerStoreRecord> lqw = buildQueryWrapper(bo);
        Page<ErpSellerStoreRecordDto> result = baseMapper.selectAllVoPage(pageQuery.build(),selectDto);
        return TableDataInfo.build(result);
    }

    /**
     * 新增店铺信息
     */
    @Override
    public Boolean insertByBo(ErpSellerStoreRecordBo bo) {
        ErpSellerStoreRecord add = BeanUtil.toBean(bo, ErpSellerStoreRecord.class);

//        add.setCreateBy(SecurityUtils.getUserId()+"");

        // 唯一性验证
        List<ErpSellerStoreRecord> list = baseMapper.selectList(new LambdaQueryWrapper<ErpSellerStoreRecord>()
                .eq(ErpSellerStoreRecord::getStoreUserName, add.getStoreUserName()));
        if (list != null || list.size() > 0) {
            if (list.get(0).getDelFlag().equals("2")){
                // 过去添加过，但被删除，则直接更新即可
                ErpSellerStoreRecord old = BeanUtil.toBean(add, ErpSellerStoreRecord.class);
                old.setId(list.get(0).getId());
                old.setDelFlag("0");
                old.setUpdateBy(SecurityUtils.getUserId()+"");
                old.setUpdateTime(new Date());
                return baseMapper.updateById(old) > 0;
            }
            // 已存在
            throw new RuntimeException("店铺已存在，请勿重复添加");
        }
        return baseMapper.insert(add) > 0;
    }

    /**
     * 修改店铺信息
     */
    @Override
    public Boolean updateByBo(ErpSellerStoreRecordBo bo) {
        ErpSellerStoreRecord update = BeanUtil.toBean(bo, ErpSellerStoreRecord.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 批量删除店铺信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            int delCount = 0;
            for (Long id : ids){
                ErpSellerStoreRecord delStore = baseMapper.selectById(id);
                // 判定店铺是否被ERP绑定，如果绑定且授权有效、或无效不超过6个月，则不能删除店铺信息
                ErpSellerStoreEmpower delStoreEmpower = empowerService.queryByStoreUserName(delStore.getStoreUserName());
                if (delStoreEmpower.getIsEmpower().equals("2")){
                    // 店铺已过期
                    long days = DateUtils.dayDistance(new Date(), delStoreEmpower.getExpireTime());
                    if (days > 180){
                        delCount += baseMapper.deleteById(id);
                    }
                }
            }
            if (delCount == 0 || delCount != ids.size()){
                throw new RuntimeException("存在已绑定、或已授权、或授权未过期超过六个月的店铺，该类店铺不允许删除");
            }
            return true;
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * @Description: 组合查询参数
     * @Author: j.zh
     * @Date: 2024/7/6
     * @param bo
     * @return
     * @Version: 4.2.0
    **/
    private LambdaQueryWrapper<ErpSellerStoreRecord> buildQueryWrapper(ErpSellerStoreRecordBo bo) {
        LambdaQueryWrapper<ErpSellerStoreRecord> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getStoreName()), ErpSellerStoreRecord::getStoreName, bo.getStoreName());
        lqw.eq(StringUtils.isNotBlank(bo.getStoreEmail()), ErpSellerStoreRecord::getStoreEmail, bo.getStoreEmail());
        lqw.like(StringUtils.isNotBlank(bo.getStoreUserName()), ErpSellerStoreRecord::getStoreUserName,
                bo.getStoreUserName());
        lqw.eq(StringUtils.isNotBlank(bo.getStorePhone()), ErpSellerStoreRecord::getStorePhone, bo.getStorePhone());
        lqw.eq(StringUtils.isNotBlank(bo.getStoreType()), ErpSellerStoreRecord::getStoreType, bo.getStoreType());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), ErpSellerStoreRecord::getCreateBy, bo.getCreateBy());
        return lqw;
    }
}
